package list;

public class MyArrayList implements MyList {

    private Object[] arr = new Object[2];
    private int i = 0;

    @Override
    public boolean add(Object data) {
        if (i >= arr.length) {
            Object[] temp = new Object[arr.length * 2];
            for (int j = 0; j < i; j++) {
                temp[j] = arr[j];
            }
            arr = temp;
        }
        arr[i] = data;
        i++;
        return true;
    }

    @Override
    public boolean add(int index, Object data) {
        if (index < i) {
            arr[index] = data;
            return true;
        } else if (index == i ) {
            arr[index] = data;
            i++;
            return true;
        } else if (index<0||index>i){
            throw new RuntimeException("越界");
        }
        return true;
    }


    @Override
    public Object remove(Object data) {
        int j=0;
        for (j = 0; j <= i; j++) {
            if (data.equals(arr[j]) & j + 1 <= i) {
                for (int y = j; y < i; y++) {
                    arr[y] = arr[y + 1];
                }
                break;
            }

        }
        if (j>=i+1){
            throw new RuntimeException("元素不存在");
        }
        i--;
        return null;
    }


    @Override
    public Object remove(int index) {
        if (index>i){
            throw new RuntimeException("越界");
        }else {
            for (int j=index;j<i;j++){
                arr[j]=arr[j+1];
            }
        }
        i--;
        return null;
    }

    @Override
    public boolean set(int index, Object data) {
        if (index>i){
            throw new RuntimeException("越界");
        }else {
            arr[index]=data;
        }
        return true;
    }

    @Override
    public Object getValue(int index) {
        if (index>i-1){
            throw new RuntimeException("越界");
        }else {
            return arr[index];
        }
    }

    @Override
    public int size() {
        return i;
    }
}